<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
                        <el-form-item label="条款名称" prop="protocolName">
                            <el-input
                                    v-model="queryParams.protocolName"
                                    placeholder="请输入条款名称"
                                    clearable
                                    @keyup.enter="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item label="协议版本" prop="version">
                            <el-input
                                    v-model="queryParams.version"
                                    placeholder="请输入协议版本"
                                    clearable
                                    @keyup.enter="handleQuery"
                            />
                        </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                        type="primary"
                        plain
                        icon="Plus"
                        @click="handleAdd"
                        v-hasPermi="['system:protocol:add']"
                >新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="success"
                        plain
                        icon="Edit"
                        :disabled="single"
                        @click="handleUpdate"
                        v-hasPermi="['system:protocol:edit']"
                >修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="danger"
                        plain
                        icon="Delete"
                        :disabled="multiple"
                        @click="handleDelete"
                        v-hasPermi="['system:protocol:remove']"
                >删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="warning"
                        plain
                        icon="Download"
                        @click="handleExport"
                        v-hasPermi="['system:protocol:export']"
                >导出</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="protocolList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="序号" type="index" width="60" align="center">
                <template #default="scope">
                    <span>{{ scope.$index + 1 }}</span>
                </template>
            </el-table-column>
                    <el-table-column label="条款名称" align="center" prop="protocolName" />
                    <el-table-column label="协议类型" align="center" prop="protocolType" :formatter="protocolTypeFormatter" />
                    <el-table-column label="协议内容" align="center" prop="content" width="200" :formatter="contentFormatter" />
                    <el-table-colum1n label="协议版本" align="center" prop="version" />
                    <el-table-column label="备注" align="center" prop="remark" width="200" :formatter="remarkFormatter" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button link type="primary" icon="View" @click="handleViewDetails(scope.row)">查看详情</el-button>
                    <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:protocol:edit']">修改</el-button>
                    <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:protocol:remove']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
                v-show="total>0"
                :total="total"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                @pagination="getList"
        />

        <!-- 添加或修改政策条款对话框 -->
        <el-dialog :title="title" v-model="open" width="600px" append-to-body v-if="open" :class="{'view-mode-dialog': isViewMode}">
            <el-form ref="protocolRef" :model="form" :rules="rules" label-width="80px">
                                <el-form-item label="条款名称" prop="protocolName">
                                    <el-input v-model="form.protocolName" :placeholder="isViewMode ? '' : '请输入条款名称'" :readonly="isViewMode" />
                                </el-form-item>
                                <el-form-item label="协议类型" prop="protocolType">
                                    <el-input v-model="form.protocolType" :placeholder="isViewMode ? '' : '请输入协议类型'" :readonly="isViewMode" />
                                </el-form-item>
                                <el-form-item label="协议内容">
                                    <editor v-model="form.content" :min-height="192" :read-only="isViewMode" :placeholder="isViewMode ? '' : '请输入内容'"/>
                                </el-form-item>
                                <el-form-item label="协议版本" prop="version">
                                    <el-input v-model="form.version" :placeholder="isViewMode ? '' : '请输入协议版本'" :readonly="isViewMode" />
                                </el-form-item>
                                <el-form-item label="备注" prop="remark">
                                    <el-input v-model="form.remark" type="textarea" :placeholder="isViewMode ? '' : '请输入内容'" :readonly="isViewMode" />
                                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm" v-show="!isViewMode">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="Protocol">
    import { listProtocol, getProtocol, delProtocol, addProtocol, updateProtocol } from "@/api/system/protocol";

    const { proxy } = getCurrentInstance();

    const protocolList = ref([]);
    const open = ref(false);
    const loading = ref(true);
    const showSearch = ref(true);
    const ids = ref([]);
    const single = ref(true);
    const multiple = ref(true);
    const total = ref(0);
    const title = ref("");
    const isViewMode = ref(false); // 新增的查看模式变量

    const data = reactive({
        form: {},
        queryParams: {
            pageNum: 1,
            pageSize: 10,
                protocolName: null,
                protocolType: null,
                content: null,
                version: null,
    },
    rules: {
    }
    });

    const { queryParams, form, rules } = toRefs(data);

    // 格式化协议类型
    function protocolTypeFormatter(row) {
        return (row.protocolType || '').toUpperCase();
    }

    // 格式化协议内容，去除HTML标签并限制长度
    function contentFormatter(row) {
        if (!row.content) return '';
        const div = document.createElement('div');
        div.innerHTML = row.content;
        const textContent = div.textContent || div.innerText || '';
        return textContent.length > 50 ? textContent.substring(0, 50) + '...' : textContent;
    }

    // 格式化备注，限制长度
    function remarkFormatter(row) {
        if (!row.remark) return '';
        return row.remark.length > 50 ? row.remark.substring(0, 50) + '...' : row.remark;
    }

    /** 查询政策条款列表 */
    function getList() {
        loading.value = true;
        listProtocol(queryParams.value).then(response => {
            protocolList.value = response.rows;
            total.value = response.total;
            loading.value = false;
        });
    }

    // 取消按钮
    function cancel() {
        open.value = false;
        isViewMode.value = false; // 关闭时重置查看模式
        reset();
    }

    // 表单重置
    function reset() {
        form.value = {
                protocolName: null,
                protocolType: null,
                content: '', // 将null改为''，确保在查看模式下不显示placeholder
                version: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                remark: null,
                delFlag: null
    };
        proxy.resetForm("protocolRef");
    }

    /** 搜索按钮操作 */
    function handleQuery() {
        queryParams.value.pageNum = 1;
        getList();
    }

    /** 重置按钮操作 */
    function resetQuery() {
        proxy.resetForm("queryRef");
        handleQuery();
    }

    // 多选框选中数据
    function handleSelectionChange(selection) {
        ids.value = selection.map(item => item.protocolId); // 将id改回protocolId
        single.value = selection.length != 1;
        multiple.value = !selection.length;
    }

    /** 新增按钮操作 */
    function handleAdd() {
        reset();
        form.value.content = ''; // 确保内容为空
        open.value = true;
        title.value = "添加政策条款";
        isViewMode.value = false; // 新增时确保不是查看模式
    }

    /** 修改按钮操作 */
    function handleUpdate(row) {
        reset();
        const _protocolId = row.protocolId || ids.value[0]; // 使用protocolId作为唯一标识
        if (_protocolId == null) {
            proxy.$modal.msgError("无法获取协议ID，请检查数据或选择一个有效的协议。");
            return;
        }
        getProtocol(_protocolId).then(response => { // 传递protocolId
            form.value = response.data;
            // 如果内容不包含HTML标签，则将其包装在<p>标签中
            if (form.value.content && !/<[a-z][\s\S]*>/i.test(form.value.content)) {
                form.value.content = `<p>${form.value.content}</p>`;
            }
            if (form.value.protocolType) {
                form.value.protocolType = form.value.protocolType.toUpperCase();
            }
            open.value = true;
            title.value = "修改政策条款";
            isViewMode.value = false; // 修改时确保不是查看模式
        });
    }

    /** 查看详情按钮操作 */
    function handleViewDetails(row) {
        reset();
        const _protocolId = row.protocolId;
        if (_protocolId == null) {
            proxy.$modal.msgError("无法获取协议ID，请检查数据或选择一个有效的协议。");
            return;
        }
        getProtocol(_protocolId).then(response => {
            form.value = response.data;
            // 如果内容不包含HTML标签，则将其设置为空字符串，以确保不显示占位符
            if (form.value.content && !/<[a-z][\s\S]*>/i.test(form.value.content)) {
                form.value.content = `<p>${form.value.content}</p>`;
            }
            if (form.value.protocolType) {
                form.value.protocolType = form.value.protocolType.toUpperCase();
            }
            open.value = true;
            title.value = "查看政策条款";
            isViewMode.value = true; // 设置为查看模式
        });
    }

    /** 提交按钮 */
    function submitForm() {
        proxy.$refs["protocolRef"].validate(valid => {
            if (valid) {
                console.log('Content being submitted to backend:', form.value.content);
                if (form.value.protocolId != null) { // 通过form.value.protocolId判断是新增还是修改
                    updateProtocol(form.value).then(response => {
                        proxy.$modal.msgSuccess("修改成功");
                        open.value = false;
                        getList();
                    });
                } else {
                    addProtocol(form.value).then(response => {
                        proxy.$modal.msgSuccess("新增成功");
                        open.value = false;
                        getList();
                    });
                }
            }
        });
    }

    /** 删除按钮操作 */
    function handleDelete(row) {
        const _protocolIds = row.protocolId || ids.value; // 使用protocolId作为唯一标识
        proxy.$modal.confirm('是否确认删除政策条款编号为"' + _protocolIds + '"的数据项？').then(function() {
            return delProtocol(_protocolIds); // 传递protocolId
        }).then(() => {
            getList();
            proxy.$modal.msgSuccess("删除成功");
        }).catch(error => {
            console.error("删除失败：", error);
            proxy.$modal.msgError("删除失败，请稍后再试。");
        });
    }

    /** 导出按钮操作 */
    function handleExport() {
        proxy.download('system/protocol/export', {
            ...queryParams.value
        }, `protocol_${new Date().getTime()}.xlsx`)
    }


    getList();
</script>

<style scoped>
.view-mode-dialog .ql-toolbar {
  display: none !important;
}

.view-mode-dialog .ql-editor {
  pointer-events: none;
  cursor: default;
}
</style>
